<template>
    <n-scrollbar x-scrollable style="max-height: 100vh">
        <CommonPage>
            <div>
                <n-form ref="form"
                        :model="searchCondition"
                        label-placement="left"
                        label-align="right"
                        label-width="80px"
                        :show-require-mark="false">
                    <div>
                        <div class="grid md:flex md:flex-wrap md:gap-x-1">
                            <n-form-item style="margin-left: 10px">
                              <label style="width: 95px;">管理员姓名：</label>
                              <n-input style="width: 170px;" v-model:value="searchCondition.name"
                                       placeholder="请输入管理员姓名" clearable/>
                            </n-form-item>
                          <n-form-item style="margin-left: 10px">
                            <label style="width: 50px;">角色：</label>
                            <n-select v-model:value="searchCondition.role" :options="roles"/>
                          </n-form-item>
                          <n-form-item style="margin-left: 10px">
                            <n-button type="primary" @click="searchByCondition">查找</n-button>
                          </n-form-item>
                          <n-form-item style="margin-left: 10px">
                            <n-button type="primary" @click="showForm = true">添加管理员</n-button>
                          </n-form-item>
                          <n-form-item style="margin-left: 10px">
                            <n-button type="error" @click="deleteSelectAdmins">批量删除</n-button>
                          </n-form-item>

                        </div>
                    </div>
                </n-form>
            </div>
          <AddAccountForm
              :roleOptions="filteredRoles"
              @update-page="searchByCondition"
              :show="showForm"
              :onClose="handleClose"/>
          <UpdateAccountForm
              :roleOptions="filteredRoles"
              :roleName="roleName"
              @update-page="searchByCondition"
              :show="showForm1"
              :onClose="handleClose"
              :attribute="currentAttribute"
          />
          <n-data-table
              remote
              :single-line="false"
              ref="table"
              :columns="columns"
              :data="adminList"
              :loading="loading"
              :pagination="paginationReactive"
              :row-key="rowKey"
              :scroll-x="900"
              @update:checked-row-keys="handleCheck"
          />
        </CommonPage>
    </n-scrollbar>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue'
import api from '@/api/admin';

import {useUserStore} from '@/store';
import {useRouter} from 'vue-router';
import AdminActions from './components/admin-actions.vue';
import {NButton} from 'naive-ui'
import AddAccountForm from './components/account-add.vue'
import UpdateAccountForm from './components/account-edit.vue'

const showForm = ref(false);
const showForm1 = ref(false);
const handleClose = () => {
  showForm.value = false;
  showForm1.value = false;
};
const currentAttribute = ref(null); // 当前编辑的属性
const adminList = ref([])
const roleName = ref("")
const role = ref("")
const userStore = useUserStore()
const router = useRouter()
const loading = ref(true)
const range = ref(null)
const value = ref("全部")
const roles = ref([])
roles.value.push(
    {
      label: '全部',
      value: -1,
    }
)
const filteredRoles = computed(() => roles.value.filter(role => role.value !== -1));
const queryRoleList = async () => {
  loading.value = true
  try {
    const res = await api.findAllRole()
    if (res.code === 200) {
      res.data.map((item) => {
        roles.value.push({
          label: item.name,
          value: item.authority
        })
      })
    } else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获取角色信息失败！")
  } finally {
    loading.value = false
  }
}
const checkedRowKeysRef = ref([]);
const handleCheck = (rowKeys) => {
  checkedRowKeysRef.value = rowKeys;
}
const rowKey = (rowData) => {
  return rowData.id
}
const option = ref([])
const searchCondition = ref({
  name: "",
  role: "全部"
});
const columns = [
  {
    type: 'selection',
    fixed: 'left',
  },
  {
    key: 'colId',
    title: '序号',
    width: 60,
  },
  {
    key: 'id',
    title: '用户编号',
    width: 70,
  },
  {
    key: 'username',
    title: '管理员名',
    width: 80,
  },
  {
    key: 'name',
    title: '姓名',
    width: 80,
  },
  {
    key: 'roleName',
    title: '角色',
    width: 80,
  },
    {
        key: 'phone',
        title: '电话',
        width: 100,
    },
    {
        key: 'email',
        title: '邮箱',
        width: 100,
    },
    {
        key: 'createTime',
        title: '创建时间',
        width: 100,
    },
    {
        key: 'lastLoginTime',
        title: '最近登录时间',
        width: 120,
    },
    {
        key: 'loginIp',
        title: '登录IP',
        width: 100,
    },
    {
        key: 'operation',
        title: '操作',
        width: 120,
        render(row) {
          return h(
              AdminActions,
              {
                onClickDelete: () => onDeleteAdmin(row),
                onClickEdit: () => onEditAdmin(row),
              }
          );
        }
    },
]
const onEditAdmin = async (admin) => {
  currentAttribute.value = admin; // 设置当前编辑的属性
  role.value=admin.role;
  await queryRole(); // 在对话框显示时查询角色信息
  showForm1.value = true; // 显示编辑窗口
}
const queryRole = async () => {
  loading.value = true;
  console.log(role.value)
  try {
    const res = await api.findNameByAuthority({ params: { authority: role.value } });
    console.log(res)
    if (res.code === 200) {
      roleName.value = res.data;
    } else {
      $message.error(res.message);
    }
  } catch (err) {
    $message.error("获取角色信息失败！");
  } finally {
    loading.value = false;
  }
};
let total = 0
const paginationReactive = reactive({
  page: 1,
  pageSize: 20,
  showSizePicker: true,
  pageSizes: [20, 50, 100],
  itemCount: 0,
  prefix: () => {
    return '查询出 ' + total + '条记录';
  },
  onChange: (page) => {
    paginationReactive.page = page;
    queryByPage()
  },
  onUpdatePageSize: (pageSize) => {
    paginationReactive.pageSize = pageSize;
    paginationReactive.page = 1;
    queryByPage()
  }
});
const deleteSelectAdmins = () => {
    if(checkedRowKeysRef.value.length <= 0) {
      $message.error("当前并未选择管理员！")
        return
    }
    $dialog.confirm({
      title: '警告',
      content: '您确定删除当前所选管理员？',
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        const ids = checkedRowKeysRef.value.join(",")
        loading.value = true
        try {
          const res = await api.deleteAdmins({params: {ids}})
          if (res.code === 200) {
            $message.success("删除所选管理员成功！")
            await searchByCondition()
          } else {
            $message.error(res.message)
          }
        } catch (err) {
          $message.error("删除所选管理员失败！")
        } finally {
          loading.value = false
        }
      },
    })
}
const searchByCondition = async ()=>{
  loading.value = true
  try {
    paginationReactive.page = 1;
    const res = await api.findPageAdmin({
      params: {
        ...searchCondition.value,
        pageNum: paginationReactive.page,
        pageSize: paginationReactive.pageSize,
      }
    })
    if (res.code === 200) {
      total = res.data.total
      paginationReactive.itemCount = total
      const baseCount = (paginationReactive.page - 1) * paginationReactive.pageSize
      adminList.value = res.data.records.map((item, i) => {
        return {
          ...item,
          colId: baseCount + i + 1,
        }
      })
    } else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("查询管理员失败！")
  }finally{
    loading.value = false
  }
}
const exportListInfo = async () => {
    const res = await api.exportAdminList({
        adminId: searchCondition.value.adminId
    })
    const contentDisposition = res.headers["content-disposition"]
    // console.log(res)
    let original_fileName = ""
    if(contentDisposition) {
        const uri = res.headers["content-disposition"].split("=")[1]
        original_fileName = window.decodeURI(uri)
    }
    const blob = new Blob([res.data], {type: "application/vnd.ms-excel"});
    if(window.navigator && window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(blob, original_fileName);
    } else {
      const fileName = original_fileName;
      const elink = document.createElement('a')
      document.body.appendChild(elink)
      elink.download = fileName;
      elink.style.display = "none"
      elink.href = window.URL.createObjectURL(blob)
      elink.click()
      window.URL.revokeObjectURL(elink.href)
      document.body.removeChild(elink)
    }
}
const onDeleteAdmin = async (admin) => {
  $dialog.confirm({
    title: '警告',
    content: '您确定删除当前管理员？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const {id} = admin
      loading.value = true
      try {
        const res = await api.deleteAdmin({id})
        if (res.code === 200) {
          $message.success("删除管理员成功！")
          await searchByCondition()
        } else {
          $message.error(res.message)
        }
      } catch (err) {
        $message.error("删除管理员失败！")
      } finally {
        loading.value = false
      }
    }
    })
}

const queryByPage = async () => {
    loading.value = true
    try {
        const res = await api.findPageAdmin(
            {
                params:{
                    pageNum:paginationReactive.page,
                    pageSize:paginationReactive.pageSize,
                }
            })
        if(res.code === 200) {
            total = res.data.total
            paginationReactive.itemCount = total
            const baseCount = (paginationReactive.page - 1)*paginationReactive.pageSize
            adminList.value = res.data.records.map((item,i)=>{
                return {...item,
                    colId: baseCount + i + 1,
                }
            })
        }
        else {
            $message.error(res.message)
        }
    } catch (err) {
      $message.error("获取管理员失败！")
    }finally{
        loading.value = false
    }
}

onMounted(()=>{
  queryByPage()
  queryRoleList()
})
</script>
<style scoped>
:deep(.n-data-table-th__title),
:deep(.n-data-table-td) {
    text-align: center;

}
:deep(.n-select) {
    width: 120px !important;
}

:deep(.two-line-description) {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2; /* 控制显示的行数 */
    overflow: hidden;
}
</style>
